import { getUserAssets, getOrderTodoCounts } from "../../service/index.js"

Page({
  data: {
    phoneNumber: '',
    dialogVisible: false,
    title: '友情提示',
    dialogMessage: '确定要退出登录吗？',
    user: wx.getStorageSync('user'),
    assets: null,
    balance: null,
    orderTodoCounts: null,
    logoutMessage: '' // 退出登录提示信息
  },

  onLoad() {
    this.checkSession()
    this.getAssets()
    this.getOrderTodoCounts()
  },

  //获取余额，积分，优惠券
  getAssets: function () {
    getUserAssets(res => {
      this.setData({
        assets: res.data.assets,
        balance: res.data.assets.balance
      })
    })
  },

  //获取商品状态数量(全部/待支付/待收货/待发货)
  getOrderTodoCounts: function () {
    getOrderTodoCounts((res) => {
      res.data.counts.all = res.data.counts.payment + res.data.counts.delivery
        + res.data.counts.received + res.data.counts.refund
      this.setData({
        orderTodoCounts: res.data.counts
      })
      console.log(this.data.orderTodoCounts, 111);
    })
  },
  // 检查登录态
  checkSession: function () {
    const user = wx.getStorageInfoSync('user')
    if (!user) {
      wx.clearStorageSync() // 清空本地存储
      wx.showToast({ title: '登录态失效，请重新登录', icon: 'none' })
    }
  },

  // 加载本地存储的手机号
  loadPhoneNumber: function () {
    const phoneNumber = wx.getStorageSync('phoneNumber') || ''
    this.setData({
      phoneNumber: phoneNumber
    })
  },

  toLogin: function () {
    wx.navigateTo({
      url: '/pages/login/index'
    })
  },
  // 退出登录按钮点击事件处理函数
  showLogoutConfirm() {
    this.setData({
      dialogVisible: true
    })
  },
  // 处理取消弹窗逻辑
  hideDialog() {
    this.setData({ dialogVisible: false })
  },

  // 确认退出逻辑
  logout() {
    wx.clearStorageSync() // 清空本地存储
    this.setData({
      phoneNumber: '',
      dialogVisible: false
    })
    wx.showToast({ title: '已退出登录', icon: 'none' });
  },
  onShow: function () {
    // 在页面显示时重新加载用户信息
    this.loadPhoneNumber();
  },
  // 点击钱包跳转到钱包页面
  toWalletPage() {
    const { balance } = this.data
    wx.navigateTo({
      url: `/pages/wallet/index?balance=${balance}`,
    })
  },
  // 在页面的事件处理函数中处理点击事件
  navigateToOrdersPage(event) {
    const type = event.currentTarget.dataset.type;// 获取点击的选项卡类型
    wx.navigateTo({
      url: '/pages/orders/index?type=' + type
    })
  },
  toAddressPage() {
    wx.navigateTo({
      url: '/pages/addressList/index',
    })
  }
})
